﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Logging;
using PropertyManagment.entity.dto;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace PropertyManagment.common.Filter {
    public class ExceptionFilter : IExceptionFilter {

        private readonly ILogger logger;

        public ExceptionFilter(ILogger<ExceptionFilter> logger) {
            this.logger = logger;
        }

        public void OnException(ExceptionContext context) {
            Exception ex = context.Exception;
            string errMsg = ex.Message;

            logger.LogError($"发生了一个异常错误。异常信息={errMsg}");

            //针对不同的自定义异常，做不同处理
            if (context.Exception.GetType() == typeof(UserLoginException)) {
                ResponseDto responseDto = new ResponseDto() {
                    code = "00001",
                    msg = errMsg
                };
                context.Result = new JsonResult(responseDto);
                context.ExceptionHandled = true;
            } else if (context.Exception.GetType() == typeof(ArgumentOutOfRangeException)) {
                ResponseDto responseDto = new ResponseDto() {
                    code = "00002",
                    msg = "信息不存在！"
                };
                context.Result = new JsonResult(responseDto);
                context.ExceptionHandled = true;
            } else if (context.Exception.GetType() == typeof(DbUpdateException)) {
                ResponseDto responseDto = new ResponseDto() {
                    code = "00003",
                    msg = "创建失败！"
                };
                context.Result = new JsonResult(responseDto);
                context.ExceptionHandled = true;
            } else {
                ResponseDto responseDto = new ResponseDto() {
                    code = "99999",
                    msg = "操作有误！"
                };
                context.Result = new JsonResult(responseDto);
                context.ExceptionHandled = true;
            }
        }
    }

    public class UserLoginException : Exception { 
        public string msg { get; set; }

        public UserLoginException(string msg) {
            this.msg = msg;
        }
        public override string Message { get { return msg; } }
    }
}
